package com.jia.leetCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Leetcode
 * @description: LeetCode 350. Intersection of Two Arrays II  两集合的交集
 * @author: STU756
 * @create: 2020-08-22 13:51
 */
public class Pro0350 {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> listAns = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>(); //<int,count>
        for(int num : nums1) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        for(int num : nums2) {
            if(map.containsKey(num)) {
                if(map.get(num) > 0)
                    listAns.add(num);
                map.put(num, map.get(num) - 1);
            }
        }
        int[] ans = new int[listAns.size()];
        for(int i = 0; i < listAns.size(); i++) {
            ans[i] = listAns.get(i);
        }
        return ans;
    }
}
